package com.cz.dao;

import com.cz.bean.App;
import com.cz.util.DbUtil;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2015/3/9.
 */
public class AppManager {
    private static final Logger logger = LoggerFactory.getLogger(AppManager.class);

    SqlSession sqlSession = DbUtil.getSessionFactory().openSession();
    AppMapper dao = sqlSession.getMapper(AppMapper.class);

    public static final int MAX_CAPACITY = 1024;

    private static AppManager instance;

    protected Cache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(MAX_CAPACITY)
            .expireAfterAccess(30, TimeUnit.DAYS)
            .build();

    static {
        try {
            instance = new AppManager();
        } catch (Exception e) {
            logger.error("Failed to init AppManager. Will EXIT...", e);
            System.exit(1);
        }
    }

    public String get(String key) {
        String res = cache.getIfPresent(key);
        if (!Strings.isNullOrEmpty(res)) return res;

        try {
            App a = dao.selectByPrimaryKey(key);
            if (a == null) return null;

            cache.put(key, a.getSecret());
            return a.getSecret();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Can't get this app from db: " + key);
        }

        return null;
    }

    public static AppManager getInstance() {
        return instance;
    }
}
